<template>
  <div class="role-route-management">
    <TopNavigation :showOrganizationSection="false" />
    <div class="page-header">
      <h2>角色路由管理</h2>
    </div>

    <div class="card">
      <div class="toolbar">
        <h3 class="section-title">路由规则管理</h3>
      </div>

      <!-- 后端路由规则数据展示 -->
      <div class="rules-container">
        <div v-if="routingRulesData.length === 0" class="empty-state">
          <div class="empty-icon">📄</div>
          <div class="empty-text">暂无数据</div>
          <div class="empty-hint">请先配置角色路由规则</div>
        </div>
        
        <div v-else class="rules-grid">
          <div v-for="rule in routingRulesData" :key="rule.id" class="rule-card">
            <!-- 角色名称和部门信息 -->
            <div class="rule-header">
              <div class="rule-title-section">
                <h3 class="role-name">
                  {{ rule.roleName }}
                  <span v-if="rule.deptName" class="department-suffix">({{ rule.deptName }})</span>
                </h3>
              </div>
              <div class="action-buttons">
                <button class="edit-btn" @click="openEditModal(rule)" title="编辑路由规则">
                  <span class="edit-icon">✏️</span>
                </button>
                <button class="delete-btn" @click="confirmDelete(rule)" title="删除路由规则">
                  <span class="delete-icon">🗑️</span>
                </button>
              </div>
            </div>
            
            <!-- 字段值展示 -->
            <div class="field-values-section">
              <h5 class="section-title">字段配置</h5>
              <div class="field-values">
                <div v-for="(value, key) in parseFieldValues(rule.fieldValues)" :key="key" class="field-item">
                  <span class="field-key">{{ key }}:</span>
                  <span class="field-value">{{ value }}</span>
                </div>
              </div>
            </div>
            
            <!-- 分配用户展示 -->
            <div class="users-section">
              <h5 class="section-title">分配用户</h5>
              <div class="users-list">
                <div v-for="user in parseAssignedUsers(rule.assignedUsers)" :key="user.id || user.name" class="user-item">
                  <div class="user-avatar">{{ getUserInitial(user.name) }}</div>
                  <div class="user-info">
                    <div class="user-name">{{ user.name }}<span v-if="user.authId" class="user-auth-id">({{ user.authId }})</span></div>
                    <div v-if="user.role" class="user-role">{{ user.role }}</div>
                  </div>
                </div>
              </div>
            </div>
            
            <!-- 统计信息 -->
            <div class="stats-section">
              <div class="stat-item">
                <span class="stat-label">字段数量:</span>
                <span class="stat-value">{{ getFieldCount(rule.fieldValues) }}</span>
              </div>
              <div class="stat-item">
                <span class="stat-label">用户数量:</span>
                <span class="stat-value">{{ getUserCount(rule.assignedUsers) }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 消息提示 -->
    <div v-if="message" :class="['message', `message-${messageType}`]">
      {{ message }}
    </div>

    <!-- 编辑模态框 -->
    <div v-if="showEditModal" class="modal-overlay" @click="cancelEdit">
      <div class="modal-content edit-modal" @click.stop>
        <div class="modal-header">
          <h3>编辑路由规则 - {{ ruleToEdit?.roleName }}</h3>
          <button class="modal-close" @click="cancelEdit">×</button>
        </div>
        <div class="modal-body">
          <div class="form-group">
            <label>分配用户：</label>
            <div class="user-selection-container">
              <div class="custom-dropdown">
                <input
                  type="text"
                  class="dropdown-search"
                  placeholder="搜索用户（用户名/AuthID）"
                  :value="editUserSearchKeyword"
                  @input="editUserSearchKeyword = $event.target.value"
                  @focus="showEditUserDropdown = true"
                  @blur="hideEditUserDropdown"
                  autocomplete="off"
                />
                <div 
                  v-if="showEditUserDropdown" 
                  class="dropdown-menu"
                >
                  <div 
                    v-for="user in getFilteredEditUsers()" 
                    :key="user.id || user.userId || user.authId"
                    class="dropdown-item"
                    @mousedown="selectEditUser(user)"
                  >
                    <div class="user-info">
                      <span class="user-name">{{ user.userName || user.cnName || user.name }}</span>
                      <span class="user-id">{{ user.authId || user.id || user.userId }}</span>
                    </div>
                  </div>
                  <div v-if="getFilteredEditUsers().length === 0" class="dropdown-item no-results">
                    无匹配结果
                  </div>
                </div>
              </div>
              <div v-if="editForm.selectedUsers.length > 0" class="selected-users">
                <div 
                  v-for="user in editForm.selectedUsers" 
                  :key="user.id || user.userId || user.authId"
                  class="user-tag"
                >
                  <span class="user-name">{{ user.userName || user.cnName || user.name }}</span>
                  <span class="user-id">({{ user.authId || user.id || user.userId }})</span>
                  <button class="remove-user" @click="removeEditUser(user)">×</button>
                </div>
              </div>
            </div>
            <div class="help-text">从该部门下的员工中选择用户</div>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn btn-secondary" @click="cancelEdit">取消</button>
          <button class="btn btn-primary" @click="handleEdit" :disabled="isEditing">
            {{ isEditing ? '保存中...' : '保存' }}
          </button>
        </div>
      </div>
    </div>

    <!-- 删除确认对话框 -->
    <div v-if="showDeleteModal" class="modal-overlay" @click="cancelDelete">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>确认删除</h3>
          <button class="modal-close" @click="cancelDelete">×</button>
        </div>
        <div class="modal-body">
          <p>确定要删除角色 <strong>{{ ruleToDelete?.roleName }}</strong> 的路由规则吗？</p>
          <p class="warning-text">此操作不可撤销，请谨慎操作。</p>
        </div>
        <div class="modal-footer">
          <button class="btn btn-secondary" @click="cancelDelete">取消</button>
          <button class="btn btn-danger" @click="handleDelete" :disabled="isDeleting">
            {{ isDeleting ? '删除中...' : '确认删除' }}
          </button>
        </div>
      </div>
    </div>
  </div>


</template>

<script setup>
import TopNavigation from '../components/TopNavigation.vue'
import { ref, onMounted } from 'vue'
import { getRoutingRules, deleteRoutingRule, updateRoutingRule } from '../services/roleRouteService.js'
import userService from '../services/userService'
import departmentService from '../services/departmentService'

// 后端路由规则数据
const routingRulesData = ref([])

// 编辑相关状态
const showEditModal = ref(false)
const ruleToEdit = ref(null)
const isEditing = ref(false)
const editForm = ref({
  assignedUsers: '',
  selectedUsers: []
})

// 用户选择相关状态
const editUserSearchKeyword = ref('')
const showEditUserDropdown = ref(false)
const departmentUsers = ref(new Map()) // 存储每个部门的用户数据
const users = ref([]) // 所有用户数据
const departments = ref([]) // 所有部门数据

// 删除相关状态
const showDeleteModal = ref(false)
const ruleToDelete = ref(null)
const isDeleting = ref(false)

// 消息提示相关
const message = ref('')
const messageType = ref('success')
const showMessage = (msg, type = 'success') => {
  message.value = msg
  messageType.value = type
  setTimeout(() => {
    message.value = ''
  }, 3000)
}

// 获取用户数据
const fetchUsers = async () => {
  try {
    const response = await userService.getUsers()
    users.value = response.data || []
  } catch (error) {
    console.error('获取用户数据失败:', error)
    users.value = []
  }
}

// 获取部门数据
const fetchDepartments = async () => {
  try {
    const response = await departmentService.getDepartments()
    departments.value = response.data || []
  } catch (error) {
    console.error('获取部门数据失败:', error)
    departments.value = []
  }
}

// 根据部门ID获取部门用户
const fetchDepartmentUsers = async (departmentId) => {
  if (!departmentId || departmentUsers.value.has(departmentId)) {
    return departmentUsers.value.get(departmentId) || []
  }
  
  try {
    const response = await userService.getUsersByDepartment(departmentId)
    let userData = []
    if (response && response.data) {
      userData = Array.isArray(response.data) ? response.data : [response.data]
    } else if (response && Array.isArray(response)) {
      userData = response
    }
    departmentUsers.value.set(departmentId, userData)
    return userData
  } catch (error) {
    console.error('获取部门用户失败:', error)
    // 如果获取部门用户失败，使用所有用户作为备选
    const fallbackUsers = users.value || []
    departmentUsers.value.set(departmentId, fallbackUsers)
    return fallbackUsers
  }
}

// 获取路由规则数据
const fetchRoutingRules = async () => {
  try {
    console.log('开始获取路由规则数据...')
    const response = await getRoutingRules()
    console.log('API响应:', response)

    // 处理API响应数据
    if (response && response.data) {
      routingRulesData.value = response.data.map(item => {
        // 解析assignedUsers字段
        let assignedUsersDisplay = ''
        try {
          if (typeof item.assignedUsers === 'string') {
            if (item.assignedUsers.startsWith('[')) {
              // 数组格式
              const users = JSON.parse(item.assignedUsers)
              assignedUsersDisplay = users.join(', ')
            } else if (item.assignedUsers.startsWith('{')) {
              // 对象格式
              const userObj = JSON.parse(item.assignedUsers)
              if (userObj.primaryUser) {
                assignedUsersDisplay = userObj.primaryUser.name
              }
            }
          }
        } catch (e) {
          assignedUsersDisplay = item.assignedUsers
        }

        return {
          id: item.id,
          roleConfigId: item.roleConfigId,
          roleName: item.roleName,
          deptId: item.deptId,
          deptName: item.deptName,
          departmentId: item.deptId, // 为了兼容现有代码中使用的departmentId字段
          fieldValues: item.fieldValues,
          assignedUsers: item.assignedUsers,
          assignedUsersDisplay
        }
      })
      showMessage('路由规则获取成功', 'success')
    } else {
      showMessage('未获取到路由规则数据', 'warning')
    }
  } catch (error) {
    console.error('获取路由规则数据失败:', error)
    showMessage('获取路由规则失败: ' + error.message, 'error')
  }
}

// 解析字段值
const parseFieldValues = (fieldValues) => {
  if (!fieldValues) return {}
  try {
    if (typeof fieldValues === 'string') {
      return JSON.parse(fieldValues)
    }
    return fieldValues
  } catch (e) {
    // 如果解析失败，返回原始字符串作为单个字段
    return { '原始值': fieldValues }
  }
}

// 解析分配用户
const parseAssignedUsers = (assignedUsers) => {
  if (!assignedUsers) return []
  try {
    if (typeof assignedUsers === 'string') {
      if (assignedUsers.startsWith('[')) {
        // 数组格式
        const users = JSON.parse(assignedUsers)
        return users.map(user => {
          if (typeof user === 'string') {
            return { name: user }
          }
          return user
        })
      } else if (assignedUsers.startsWith('{')) {
        // 对象格式
        const userObj = JSON.parse(assignedUsers)
        if (userObj.primaryUser) {
          return [userObj.primaryUser]
        }
        return [userObj]
      } else {
        // 简单字符串
        return [{ name: assignedUsers }]
      }
    }
    return Array.isArray(assignedUsers) ? assignedUsers : [assignedUsers]
  } catch (e) {
    return [{ name: assignedUsers }]
  }
}

// 获取用户名首字母
const getUserInitial = (name) => {
  if (!name) return '?'
  return name.charAt(0).toUpperCase()
}

// 获取字段数量
const getFieldCount = (fieldValues) => {
  const parsed = parseFieldValues(fieldValues)
  return Object.keys(parsed).length
}

// 获取用户数量
const getUserCount = (assignedUsers) => {
  const parsed = parseAssignedUsers(assignedUsers)
  return parsed.length
}

// 用户选择相关方法
// 获取过滤后的编辑用户列表
const getFilteredEditUsers = () => {
  if (!ruleToEdit.value?.departmentId) {
    // 如果没有部门ID，使用所有用户
    const searchKeyword = editUserSearchKeyword.value.toLowerCase().trim()
    if (!searchKeyword) {
      return users.value
    }
    return users.value.filter(user => {
      const userName = (user.userName || user.cnName || user.name || '').toLowerCase()
      const authId = (user.authId || user.id || user.userId || '').toString().toLowerCase()
      return userName.includes(searchKeyword) || authId.includes(searchKeyword)
    })
  }
  
  // 从departmentUsers中获取该部门的用户数据
  const deptUsers = departmentUsers.value.get(ruleToEdit.value.departmentId) || []
  const searchKeyword = editUserSearchKeyword.value.toLowerCase().trim()
  
  if (!searchKeyword) {
    return deptUsers
  }
  
  return deptUsers.filter(user => {
    const userName = (user.userName || user.cnName || user.name || '').toLowerCase()
    const authId = (user.authId || user.id || user.userId || '').toString().toLowerCase()
    return userName.includes(searchKeyword) || authId.includes(searchKeyword)
  })
}

// 选择编辑用户
const selectEditUser = (user) => {
  // 检查用户是否已经被选择
  const isAlreadySelected = editForm.value.selectedUsers.some(selectedUser => 
    (selectedUser.id || selectedUser.userId || selectedUser.authId) === 
    (user.id || user.userId || user.authId)
  )
  
  if (!isAlreadySelected) {
    editForm.value.selectedUsers.push(user)
  }
  
  editUserSearchKeyword.value = ''
  showEditUserDropdown.value = false
}

// 移除编辑用户
const removeEditUser = (userToRemove) => {
  editForm.value.selectedUsers = editForm.value.selectedUsers.filter(user => 
    (user.id || user.userId || user.authId) !== 
    (userToRemove.id || userToRemove.userId || userToRemove.authId)
  )
}

// 隐藏编辑用户下拉框
const hideEditUserDropdown = () => {
  setTimeout(() => {
    showEditUserDropdown.value = false
  }, 200)
}

// 编辑功能
const openEditModal = async (rule) => {
  ruleToEdit.value = rule
  
  // 重置编辑状态
  editUserSearchKeyword.value = ''
  showEditUserDropdown.value = false
  editForm.value.selectedUsers = []
  
  // 如果有部门ID，获取该部门的用户数据
  if (rule.departmentId) {
    await fetchDepartmentUsers(rule.departmentId)
  }
  
  // 解析当前分配的用户并初始化选中状态
  const currentUsers = parseAssignedUsers(rule.assignedUsers)
  if (currentUsers.length > 0) {
    // 尝试从部门用户或所有用户中匹配当前分配的用户
    const availableUsers = rule.departmentId ? 
      (departmentUsers.value.get(rule.departmentId) || []) : 
      users.value
    
    currentUsers.forEach(currentUser => {
      // 尝试通过用户名匹配
      const matchedUser = availableUsers.find(user => 
        (user.userName || user.cnName || user.name) === currentUser.name ||
        (user.id || user.userId || user.authId) === (currentUser.id || currentUser.userId || currentUser.authId)
      )
      
      if (matchedUser) {
        editForm.value.selectedUsers.push(matchedUser)
      } else {
        // 如果找不到匹配的用户，创建一个临时用户对象
        editForm.value.selectedUsers.push({
          name: currentUser.name,
          userName: currentUser.name,
          id: currentUser.id || `temp_${Date.now()}_${Math.random()}`
        })
      }
    })
  }
  
  // 初始化编辑表单，将当前的assignedUsers值填入（保持向后兼容）
  editForm.value.assignedUsers = rule.assignedUsers || ''
  showEditModal.value = true
}

const cancelEdit = () => {
  showEditModal.value = false
  ruleToEdit.value = null
  isEditing.value = false
  editForm.value.assignedUsers = ''
  editForm.value.selectedUsers = []
  editUserSearchKeyword.value = ''
  showEditUserDropdown.value = false
}

const handleEdit = async () => {
  if (!ruleToEdit.value) return
  
  isEditing.value = true
  try {
    // 构建分配用户数据
    let assignedUsersData = ''
    
    if (editForm.value.selectedUsers.length > 0) {
      // 使用新的用户选择数据
      const userList = editForm.value.selectedUsers.map(user => ({
        id: user.id || user.userId || user.authId,
        name: user.userName || user.cnName || user.name,
        authId: user.authId || user.id || user.userId
      }))
      assignedUsersData = JSON.stringify(userList)
    } else if (editForm.value.assignedUsers.trim()) {
      // 如果没有选择用户但有文本输入，使用文本输入（向后兼容）
      assignedUsersData = editForm.value.assignedUsers.trim()
    }
    
    // 构建更新数据
    const updateData = {
      roleConfigId: ruleToEdit.value.roleConfigId,
      roleName: ruleToEdit.value.roleName,
      fieldValues: ruleToEdit.value.fieldValues,
      assignedUsers: assignedUsersData
    }
    
    await updateRoutingRule(ruleToEdit.value.id, updateData)
    
    // 更新本地数据
    const index = routingRulesData.value.findIndex(rule => rule.id === ruleToEdit.value.id)
    if (index !== -1) {
      routingRulesData.value[index].assignedUsers = updateData.assignedUsers
      // 重新解析显示用户信息
      routingRulesData.value[index].assignedUsersDisplay = updateData.assignedUsers
    }
    
    showMessage('路由规则更新成功', 'success')
    cancelEdit()
  } catch (error) {
    console.error('更新路由规则失败:', error)
    showMessage('更新路由规则失败', 'error')
    isEditing.value = false
  }
}

// 确认删除
const confirmDelete = (rule) => {
  ruleToDelete.value = rule
  showDeleteModal.value = true
}

// 取消删除
const cancelDelete = () => {
  showDeleteModal.value = false
  ruleToDelete.value = null
  isDeleting.value = false
}

// 执行删除
const handleDelete = async () => {
  if (!ruleToDelete.value) return
  
  isDeleting.value = true
  try {
    await deleteRoutingRule(ruleToDelete.value.id)
    showMessage(`角色 "${ruleToDelete.value.roleName}" 的路由规则删除成功`, 'success')
    
    // 从列表中移除已删除的项目
    routingRulesData.value = routingRulesData.value.filter(
      rule => rule.id !== ruleToDelete.value.id
    )
    
    cancelDelete()
  } catch (error) {
    console.error('删除路由规则失败:', error)
    showMessage('删除失败: ' + (error.message || '未知错误'), 'error')
    isDeleting.value = false
  }
}

// 组件挂载时获取数据
onMounted(async () => {
  // 并行获取所有需要的数据
  await Promise.all([
    fetchRoutingRules(),
    fetchUsers(),
    fetchDepartments()
  ])
})
</script>

<style scoped>
.role-route-management {
  width: 100%;
  padding: var(--spacing-xl);
}

.page-header {
  margin-bottom: var(--spacing-xl);
  display: flex;
  align-items: center;
  gap: var(--spacing-md);
}

.page-header h2 {
  font-size: var(--font-size-xl);
  font-weight: 600;
  color: var(--text-primary);
  margin: 0;
}

/* 卡片样式继承 */
.card {
  background-color: var(--bg-white);
  border-radius: var(--border-radius-md);
  box-shadow: var(--shadow-base);
  overflow: hidden;
  transition: box-shadow 0.3s ease;
}

.card:hover {
  box-shadow: var(--shadow-md);
}

/* 工具栏样式继承 */
.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: var(--spacing-lg);
  border-bottom: 1px solid var(--border-base);
  flex-wrap: wrap;
  gap: var(--spacing-lg);
}

/* 搜索容器样式继承 */
.search-container {
  display: flex;
  gap: var(--spacing-sm);
  align-items: center;
  flex: 1;
  min-width: 280px;
}

/* 规则容器样式 */
.rules-container {
  padding: var(--spacing-lg);
}

.rules-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
  gap: var(--spacing-lg);
}

/* 规则卡片样式 */
.rule-card {
  background: var(--bg-white);
  border: 1px solid var(--border-base);
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.rule-card:hover {
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  transform: translateY(-4px);
  border-color: #e0f2fe;
}

/* 规则头部 */
.rule-header {
  margin-bottom: var(--spacing-lg);
  padding-bottom: var(--spacing-md);
  border-bottom: 2px solid var(--primary-color);
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.rule-title-section {
  flex: 1;
}

.role-name {
  margin: 0 0 var(--spacing-xs) 0;
  font-size: 22px;
  font-weight: 600;
  color: var(--primary-color);
  display: flex;
  align-items: center;
  gap: 8px;
}

.department-suffix {
  font-size: 14px;
  color: var(--text-secondary);
  font-weight: 500;
  background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
  padding: 4px 8px;
  border-radius: 6px;
  border: 1px solid #bae6fd;
  transition: all 0.3s ease;
}

.department-suffix:hover {
  background: linear-gradient(135deg, #e0f2fe 0%, #bae6fd 100%);
  border-color: #0ea5e9;
  color: var(--primary-color);
}

.department-info {
  display: flex;
  align-items: center;
  gap: var(--spacing-xs);
  margin-top: var(--spacing-xs);
}

.department-label {
  font-size: var(--font-size-sm);
  color: var(--text-secondary);
  font-weight: 500;
}

.department-name {
  font-size: var(--font-size-sm);
  color: var(--text-primary);
  background-color: var(--bg-gray-50);
  padding: var(--spacing-xs) var(--spacing-sm);
  border-radius: var(--border-radius-sm);
  font-weight: 500;
}

/* 操作按钮容器 */
.action-buttons {
  display: flex;
  gap: var(--spacing-xs);
}

/* 编辑和删除按钮 */
.edit-btn,
.delete-btn {
  background: none;
  border: none;
  cursor: pointer;
  padding: 8px;
  border-radius: 6px;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 36px;
  height: 36px;
}

.edit-btn:hover {
  background-color: #e3f2fd;
  transform: scale(1.1);
}

.delete-btn:hover {
  background-color: #fee;
  transform: scale(1.1);
}

.edit-icon {
  font-size: 18px;
  color: #2196f3;
}

.delete-icon {
  font-size: 18px;
  color: #e74c3c;
}

/* 字段值部分 */
.field-values-section {
  margin-bottom: var(--spacing-lg);
  background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
  border: 2px solid #e2e8f0;
  border-radius: 12px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.field-values-section:hover {
  background: linear-gradient(135deg, #f1f5f9 0%, #e2e8f0 100%);
  border-color: #cbd5e1;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.field-values {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-sm);
}

.field-item {
  display: flex;
  align-items: center;
  padding: var(--spacing-sm);
  background: var(--bg-light);
  border-radius: var(--border-radius-md);
  border-left: 3px solid var(--primary-color);
}

.field-key {
  font-weight: 500;
  color: var(--text-regular);
  margin-right: var(--spacing-sm);
  min-width: 80px;
}

.field-value {
  color: var(--text-primary);
  flex: 1;
}

/* 用户部分 */
.users-section {
  margin-bottom: var(--spacing-lg);
  background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
  border: 2px solid #bae6fd;
  border-radius: 12px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.users-section:hover {
  background: linear-gradient(135deg, #e0f2fe 0%, #bae6fd 100%);
  border-color: #0ea5e9;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.users-list {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-sm);
}

.user-item {
  display: flex;
  align-items: center;
  padding: var(--spacing-sm);
  background: var(--bg-light);
  border-radius: var(--border-radius-md);
  gap: var(--spacing-sm);
  border: 1px solid var(--border-base);
  transition: all 0.3s ease;
}

.user-item:hover {
  background: var(--bg-hover);
  border-color: var(--primary-color);
  transform: translateY(-1px);
  box-shadow: var(--shadow-sm);
}

.user-avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background: var(--primary-color);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 600;
  font-size: var(--font-size-sm);
}

.user-info {
  flex: 1;
}

.user-name {
  font-weight: 500;
  color: var(--text-primary);
  margin-bottom: 2px;
}

.user-auth-id {
  font-size: var(--font-size-sm);
  color: var(--text-secondary);
  font-style: italic;
  margin-left: 4px;
}

.user-role {
  font-size: var(--font-size-sm);
  color: var(--text-secondary);
}

/* 统计部分 */
.stats-section {
  display: flex;
  gap: var(--spacing-md);
  padding: 16px;
  margin-top: 16px;
  background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%);
  border: 2px solid #f59e0b;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.stats-section:hover {
  background: linear-gradient(135deg, #fde68a 0%, #fcd34d 100%);
  border-color: #d97706;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  flex: 1;
  padding: var(--spacing-sm);
  background: rgba(255, 255, 255, 0.8);
  border-radius: var(--border-radius-md);
  border: 1px solid #f59e0b;
}

.stat-label {
  font-size: var(--font-size-sm);
  color: #92400e;
  margin-bottom: 4px;
  font-weight: 600;
}

.stat-value {
  font-size: var(--font-size-lg);
  font-weight: 700;
  color: #92400e;
}

.section-title {
  font-size: var(--font-size-base);
  font-weight: 600;
  color: var(--text-primary);
  margin: 0 0 var(--spacing-sm) 0;
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  animation: fadeIn 0.3s ease;
}

.modal-content {
  background: var(--bg-white);
  border-radius: var(--border-radius-lg);
  box-shadow: var(--shadow-lg);
  max-width: 400px;
  width: 90%;
  max-height: 90vh;
  overflow: hidden;
  animation: slideIn 0.3s ease;
}

.edit-modal {
  max-width: 500px;
}

/* 表单组样式 */
.form-group {
  margin-bottom: var(--spacing-lg);
}

.form-group label {
  display: block;
  margin-bottom: var(--spacing-sm);
  font-weight: 500;
  color: var(--text-primary);
}

.form-control {
  width: 100%;
  padding: var(--spacing-sm);
  border: 1px solid var(--border-base);
  border-radius: var(--border-radius-md);
  font-size: var(--font-size-base);
  transition: border-color 0.3s ease;
  resize: vertical;
}

.form-control:focus {
  outline: none;
  border-color: var(--primary-color);
  box-shadow: 0 0 0 2px rgba(74, 144, 226, 0.2);
}

.help-text {
  margin-top: var(--spacing-xs);
  font-size: var(--font-size-sm);
  color: var(--text-secondary);
}

/* 用户选择组件样式 - 参考RoutingRules.vue设计 */
.user-selection-container {
  position: relative;
}

.custom-dropdown {
  position: relative;
  width: 100%;
}

.dropdown-search {
  width: 100%;
  padding: 12px 16px;
  border: 2px solid #e1e8ed;
  border-radius: 10px;
  background: linear-gradient(135deg, #ffffff 0%, #f8fafc 100%);
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  box-sizing: border-box;
  position: relative;
  overflow: hidden;
}

.dropdown-search::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.4), transparent);
  transition: left 0.5s ease;
}

.dropdown-search:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1), 0 4px 12px rgba(59, 130, 246, 0.15);
  transform: translateY(-1px);
  background: linear-gradient(135deg, #ffffff 0%, #f0f9ff 100%);
}

.dropdown-search:focus::before {
  left: 100%;
}

.dropdown-menu {
  position: absolute;
  top: calc(100% + 4px);
  left: 0;
  right: 0;
  background: linear-gradient(135deg, #ffffff 0%, #f8fafc 100%);
  border: 2px solid #e1e8ed;
  border-radius: 12px;
  box-shadow: 0 10px 40px rgba(0, 0, 0, 0.1), 0 4px 20px rgba(0, 0, 0, 0.05);
  max-height: 240px;
  overflow-y: auto;
  z-index: 1000;
  backdrop-filter: blur(8px);
  animation: dropdownSlideIn 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
}

.dropdown-menu::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 1px;
  background: linear-gradient(90deg, transparent, #3b82f6, transparent);
}

@keyframes dropdownSlideIn {
  from {
    opacity: 0;
    transform: translateY(-8px) scale(0.95);
  }
  to {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}

.dropdown-item {
  padding: 12px 16px;
  cursor: pointer;
  border-bottom: 1px solid rgba(226, 232, 240, 0.5);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  overflow: hidden;
  font-weight: 500;
}

.dropdown-item::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(59, 130, 246, 0.1), transparent);
  transition: left 0.4s ease;
}

.dropdown-item:hover {
  background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
  color: #1e40af;
  padding-left: 20px;
  border-left: 3px solid #3b82f6;
}

.dropdown-item:hover::before {
  left: 100%;
}

.dropdown-item:last-child {
  border-bottom: none;
  border-radius: 0 0 10px 10px;
}

.dropdown-item:first-child {
  border-radius: 10px 10px 0 0;
}

.dropdown-item.no-results {
  color: #64748b;
  font-style: italic;
  cursor: default;
  text-align: center;
  background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
}

.dropdown-item.no-results:hover {
  background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
  color: #64748b;
  padding-left: 16px;
  border-left: none;
}

.user-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
  position: relative;
}

.user-info .user-name {
  font-weight: 600;
  color: #1e293b;
  font-size: 14px;
  transition: color 0.3s ease;
}

.dropdown-item:hover .user-name {
  color: #1e40af;
}

.user-info .user-id {
  font-size: 12px;
  color: #64748b;
  opacity: 0.9;
  font-weight: 500;
  padding: 2px 8px;
  background: rgba(148, 163, 184, 0.1);
  border-radius: 6px;
  display: inline-block;
  width: fit-content;
  transition: all 0.3s ease;
}

.dropdown-item:hover .user-id {
  background: rgba(59, 130, 246, 0.1);
  color: #3b82f6;
}

.selected-users {
  margin-top: 16px;
  padding: 16px;
  background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
  border-radius: 12px;
  border: 1px solid #bae6fd;
  box-shadow: 0 2px 8px rgba(14, 165, 233, 0.1);
  transition: all 0.3s ease;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.selected-users:hover {
  box-shadow: 0 4px 12px rgba(14, 165, 233, 0.15);
}

.user-tag {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  background: linear-gradient(135deg, #ffffff 0%, #f0f9ff 100%);
  border: 1px solid #0ea5e9;
  border-radius: 20px;
  font-size: 13px;
  box-shadow: 0 2px 4px rgba(14, 165, 233, 0.1);
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
  margin-bottom: 8px;
  margin-right: 8px;
  display: inline-flex;

}

.user-tag::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 3px;
  height: 100%;
  background: linear-gradient(180deg, #0ea5e9 0%, #0284c7 100%);
}

.user-tag:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(14, 165, 233, 0.2);
  border-color: #0284c7;
}

.user-tag .user-name {
  color: #0369a1;
  font-weight: 600;
  margin-left: 3px;
}

.user-tag .user-id {
  color: #0369a1;
  opacity: 0.8;
  font-weight: 500;
  background: rgba(3, 105, 161, 0.1);
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 11px;
}

.remove-user {
  background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
  color: white;
  border: none;
  border-radius: 50%;
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  font-size: 12px;
  font-weight: bold;
  transition: all 0.3s ease;
  box-shadow: 0 2px 4px rgba(239, 68, 68, 0.2);

}

.remove-user:hover {
  background: linear-gradient(135deg, #dc2626 0%, #b91c1c 100%);
  transform: scale(1.05) rotate(90deg);
  box-shadow: 0 4px 8px rgba(239, 68, 68, 0.3);
}

/* 帮助文本样式 */
.help-text {
  margin-top: 8px;
  font-size: 12px;
  color: #64748b;
  font-style: italic;
  padding: 8px 12px;
  background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
  border-radius: 6px;
  border-left: 3px solid #94a3b8;
  transition: all 0.3s ease;
}

.help-text:hover {
  background: linear-gradient(135deg, #f1f5f9 0%, #e2e8f0 100%);
  border-left-color: #64748b;
}

.modal-header {
  padding: var(--spacing-lg);
  border-bottom: 1px solid var(--border-base);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-header h3 {
  margin: 0;
  font-size: var(--font-size-lg);
  font-weight: 600;
  color: var(--text-primary);
}

.modal-close {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: var(--text-secondary);
  padding: 0;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: var(--border-radius-md);
  transition: all 0.3s ease;
}

.modal-close:hover {
  background-color: var(--bg-hover);
  color: var(--text-primary);
}

.modal-body {
  padding: var(--spacing-lg);
}

.modal-body p {
  margin: 0 0 var(--spacing-md) 0;
  color: var(--text-primary);
  line-height: 1.5;
}

.modal-body p:last-child {
  margin-bottom: 0;
}

.warning-text {
  color: #e74c3c !important;
  font-size: var(--font-size-sm);
  font-weight: 500;
}

.modal-footer {
  padding: var(--spacing-lg);
  border-top: 1px solid var(--border-base);
  display: flex;
  gap: var(--spacing-md);
  justify-content: flex-end;
}

.btn-secondary {
  background-color: var(--bg-light);
  color: var(--text-primary);
  border: 1px solid var(--border-base);
}

.btn-secondary:hover {
  background-color: var(--bg-hover);
  border-color: var(--text-secondary);
}

.btn-primary {
  background-color: var(--primary-color);
  color: white;
  border: 1px solid var(--primary-color);
}

.btn-primary:hover:not(:disabled) {
  background-color: #0056b3;
  border-color: #004085;
}

.btn-danger {
  background-color: #e74c3c;
  color: white;
  border: 1px solid #e74c3c;
}

.btn-danger:hover:not(:disabled) {
  background-color: #c0392b;
  border-color: #c0392b;
}

.btn-danger:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
}

/* 动画效果 */
@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateY(-20px) scale(0.95);
  }
  to {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}

/* 空状态提示 */
.empty-state {
  text-align: center;
  padding: 80px 20px;
  color: var(--text-secondary);
  min-height: 300px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: var(--spacing-md);
  background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
  border-radius: 16px;
  border: 2px dashed #cbd5e1;
  margin: 20px 0;
  transition: all 0.3s ease;
}

.empty-state:hover {
  background: linear-gradient(135deg, #f1f5f9 0%, #e2e8f0 100%);
  border-color: #94a3b8;
}

.empty-icon {
  font-size: 64px;
  opacity: 0.6;
  margin-bottom: var(--spacing-sm);
  transition: all 0.3s ease;
}

.empty-state:hover .empty-icon {
  transform: scale(1.1);
  opacity: 0.8;
}

.empty-text {
  font-size: 18px;
  font-weight: 600;
  color: #475569;
  margin-bottom: 8px;
}

.empty-hint {
  font-size: 14px;
  color: #64748b;
  font-style: italic;
  padding: 8px 16px;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 8px;
  border: 1px solid #e2e8f0;
}

/* 按钮样式 */
.btn {
  padding: var(--spacing-sm) var(--spacing-md);
  border: none;
  border-radius: var(--border-radius-md);
  font-size: var(--font-size-base);
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  text-decoration: none;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: var(--spacing-xs);
}

.btn-primary {
  background-color: var(--primary-color);
  color: white;
}

.btn-primary:hover {
  background-color: var(--primary-hover);
  transform: translateY(-1px);
  box-shadow: var(--shadow-md);
}

.section-title {
  font-size: var(--font-size-lg);
  font-weight: 600;
  color: #1e40af;
  margin: 0 0 12px 0;
  text-transform: uppercase;
  letter-spacing: 0.5px;
  padding-bottom: 8px;
  border-bottom: 2px solid transparent;
  background: linear-gradient(90deg, #3b82f6, #1d4ed8) no-repeat bottom;
  background-size: 40px 2px;
  position: relative;
  transition: all 0.3s ease;
}

.section-title::after {
  content: '';
  position: absolute;
  bottom: -2px;
  left: 40px;
  width: 20px;
  height: 2px;
  background: linear-gradient(90deg, #1d4ed8, transparent);
  transition: width 0.3s ease;
}

.field-values-section:hover .section-title::after {
  width: 60px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .toolbar {
    flex-direction: column;
    align-items: stretch;
  }

  .search-container {
    width: 100%;
  }

  .rules-grid {
    grid-template-columns: 1fr;
    gap: var(--spacing-md);
  }

  .rule-card {
    padding: var(--spacing-md);
  }

  .stats-section {
    flex-direction: column;
    gap: var(--spacing-sm);
  }

  .field-item {
    flex-direction: column;
    align-items: flex-start;
    gap: var(--spacing-xs);
  }

  .field-key {
    min-width: auto;
    margin-right: 0;
  }
}

/* 消息提示样式 */
.message {
  position: fixed;
  top: 20px;
  right: 20px;
  padding: var(--spacing-md) var(--spacing-lg);
  border-radius: var(--border-radius-md);
  font-weight: 500;
  z-index: 1001;
  animation: slideInRight 0.3s ease;
  box-shadow: var(--shadow-md);
  max-width: 400px;
}

.message-success {
  background-color: #d4edda;
  color: #155724;
  border: 1px solid #c3e6cb;
}

.message-error {
  background-color: #f8d7da;
  color: #721c24;
  border: 1px solid #f5c6cb;
}

.message-warning {
  background-color: #fff3cd;
  color: #856404;
  border: 1px solid #ffeaa7;
}

@keyframes slideInRight {
  from {
    opacity: 0;
    transform: translateX(100%);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
}
</style>